import { ref } from 'vue';

export function useWeight(showPicker, columns) {
  const onConfirm = ({ selectedOptions }) => {
    showPicker.value = false;

    const fieldText = selectedOptions[0].text;
    const fieldValue = selectedOptions[0].value;

    if (columns.value.length === 3) {
      imperialUnit.value = Number(fieldValue);
      imperialLabel.value = fieldText;

      imperialToMetric();

      return;
    }

    metricUnit.value = Number(fieldValue);
    metricLabel.value = fieldText;

    metricToImperial();
  };

  const metric = ref(0);
  const metricUnit = ref(1);
  const metricLabel = ref('g');

  const imperial = ref(0);
  const imperialUnit = ref(1);
  const imperialLabel = ref('oz');

  function metricToImperial() {
    // metric to centimeter than to inch
    const inchNum = Number(
      ((metric.value * metricUnit.value) / 28.3495).toFixed(2)
    );
    imperial.value = Number((inchNum / imperialUnit.value).toFixed(2));
  }

  function imperialToMetric() {
    // imperial to inch than to centimeter
    const centimeterNum = Number(
      imperial.value * imperialUnit.value * 28.3495
    ).toFixed(2);
    metric.value = Number((centimeterNum / metricUnit.value).toFixed(2));
  }

  return {
    metric,
    metricUnit,
    metricLabel,

    imperial,
    imperialUnit,
    imperialLabel,

    onConfirm,

    metricToImperial,
    imperialToMetric,
  };
}
